package com.fyy.netty.chapter02.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author fyy
 * @Description
 * @Date 2021/4/26 9:01
 */
@Slf4j
public class NettyServer {

    public static void main(String[] args) {
        //声明一个服务器的启动器，组装Netty组件
        new ServerBootstrap()
                //工作组可以添加组线程组及工作线程组
                .group(new NioEventLoopGroup(1),new NioEventLoopGroup(10))
                //实现的事件，比如BIO、NIO
                .channel(NioServerSocketChannel.class)
                //boss负责处理连接，worker(child)负责业务处理
                .childHandler(
                    //Channel客户端读写通道,Initializer初始化Handler
                    new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new StringDecoder()); //解码处理器
                        sc.pipeline().addLast(new ChannelInboundHandlerAdapter(){ //自定义的Handler
                            //处理读事件
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("服务器读取的内容：{}",msg);
                            }
                        });
                    }
                })
                .bind("127.0.0.1",8080); //绑定服务器及端口
    }

}
